package com.laker.autotest.core;

import com.laker.autotest.utils.TestNGUtil;
import lombok.extern.slf4j.Slf4j;
import org.testng.ITestResult;
import org.testng.internal.Utils;
import org.testng.reporters.EmailableReporter2;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.newBufferedWriter;

@Slf4j
public class LakerEmailableReporter2 extends EmailableReporter2 {

    @Override
    protected PrintWriter createWriter(String outdir) throws IOException {
        outdir = TestNGUtil.getReportDir();
        new File(outdir).mkdirs();
        return new PrintWriter(newBufferedWriter(new File(outdir, TestNGUtil.getReportFileName()).toPath(), UTF_8));
    }

    @Override
    protected void writeStylesheet() {
        writer.print("<style type=\"text/css\">");
//        writer.print("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show}");
        writer.print("table {margin-bottom:10px;border-collapse:collapse;empty-cells:show; width: 400px;}"); // 设置表格宽度为200px
        writer.print("th,td {border:1px solid #009;padding:.25em .5em}");
        writer.print("th {vertical-align:bottom}");
        writer.print("td {vertical-align:top}");
        writer.print("table a {font-weight:bold}");
        writer.print(".stripe td {background-color: #E6EBF9}");
        writer.print(".num {text-align:right}");
        writer.print(".passedodd td {background-color: #3F3}");
        writer.print(".passedeven td {background-color: #0A0}");
        writer.print(".skippedodd td {background-color: #DDD}");
        writer.print(".skippedeven td {background-color: #CCC}");
        writer.print(".failedodd td,.attn {background-color: #F33}");
        writer.print(".failedeven td,.stripe .attn {background-color: #D00}");
        writer.print(".stacktrace {white-space:pre;font-family:monospace}");
        writer.print(".totop {font-size:85%;text-align:center;border-bottom:2px solid #000}");
        writer.print(".invisible {display:none}");
        writer.println("</style>");
    }

    @Override
    protected void writeScenarioDetails() {
        int scenarioIndex = 0;
        for (SuiteResult suiteResult : suiteResults) {
            for (TestResult testResult : suiteResult.getTestResults()) {
                writer.print("<h2>");
                writer.print(Utils.escapeHtml(testResult.getTestName()));
                writer.print("</h2>");
                scenarioIndex += writeScenarioDetails(testResult.getFailedTestResults(), scenarioIndex);
            }
        }
    }

    private int writeScenarioDetails(List<ClassResult> classResults, int startingScenarioIndex) {
        int scenarioIndex = startingScenarioIndex;
        for (ClassResult classResult : classResults) {
            String className = classResult.getClassName();
            for (MethodResult methodResult : classResult.getMethodResults()) {
                List<ITestResult> results = methodResult.getResults();
                assert !results.isEmpty();

                String label =
                        Utils.escapeHtml(
                                className + "#" + results.iterator().next().getMethod().getMethodName());
                for (ITestResult result : results) {
                    writeScenario(scenarioIndex, label, result);
                    scenarioIndex++;
                }
            }
        }

        return scenarioIndex - startingScenarioIndex;
    }

    private void writeScenario(int scenarioIndex, String label, ITestResult result) {
        writer.print("<h3 id=\"m");
        writer.print(scenarioIndex);
        writer.print("\">");
        writer.print(label);
        writer.print("</h3>");

//        writer.print("<table class=\"result\">");
        writer.print("<table style=\"width: 400px;\">");

        boolean hasRows = false;

        // Write exception (if any)
        Throwable throwable = result.getThrowable();
        if (throwable != null) {
            // 表格头 异常
            writer.print("<tr><th style=\"width: 200px;\">");
            writer.print(
                    (result.getStatus() == ITestResult.SUCCESS ? "Expected Exception" : "Exception"));
            writer.print("</th>");
            // 表格头 截图
            writer.print("<th style=\"width: 200px;\">"); // 设置固定宽度，以px为单位
            writer.print("Screenshot");
            writer.print("</th></tr>");

            writer.print("<tr><td style=\"width: 200px;\">"); // 设置固定宽度，以px为单
            writeStackTrace(throwable);
            writer.print("</td>");

            writer.print("<td style=\"width: 200px;\">"); // 设置固定宽度，以px为单位
            File file = new File(TestNGUtil.getScreenShotPath(result));
            if (file.exists()) {
                writer.print("<img src=\"");
                writer.print("../" + file.getPath());
                writer.print("\" style=\"width: 200px; height: auto;\"/>");
            } else {
                writer.print("No screenshot");
            }
            writer.print("</td></tr>");

            hasRows = true;
        }

        if (!hasRows) {
            writer.print("<tr><th");
            writer.print(" class=\"invisible\"/></tr>");
        }

        writer.print("</table>");
        writer.println("<p class=\"totop\"><a href=\"#summary\">back to summary</a></p>");
    }

}
